class Main < Gtk::Window

	attr_reader :book, :text, :dirty
	attr_accessor :filename

	def initialize
		$main = self
		super
		build_window

		self.dirty = false
		@on_fullscreen = false
		@filename = $conf.last_file
		begin
			@book = YAML::load(File.open(@filename))
			@chapterlist.refresh_buttons
			@text.formatted_text = @book.chapters[0].text
			self.title = @book.title
		rescue Errno::ENOENT, TypeError
			@filename = nil
			NewBookButton.new_book(true)
		end
	end

	def save_book
		return if not @filename
		@book.chapters[@chapterlist.current_chapter].text = @text.formatted_text
		f = File.open(@filename, 'w')
		f.print @book.to_yaml
		f.close
		self.dirty = false
	end

	def book=(b)
		@text.clear
		@book = b
		@chapterlist.refresh_buttons
		@chapterlist.set_current_chapter(0, false)
		save_book
		$conf.last_file = @filename
		$conf.save
		self.title = 'Bookwrite - ' + @book.title
	end

	def dirty=(b)
		begin
			if b
				self.title = '*' + @book.title
			else
				self.title = @book.title
			end
		rescue; end
		@dirty = b
	end

	def open_book
		save_book if @filename
		dialog = Gtk::FileChooserDialog.new("Open File",
                                    self,
                                    Gtk::FileChooser::ACTION_OPEN,
                                    nil,
                                    [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL],
                                    [Gtk::Stock::SAVE, Gtk::Dialog::RESPONSE_ACCEPT])
		filter = Gtk::FileFilter.new
		filter.name = _('BookWrite files (*.bw)')
		filter.add_pattern('*.bw')
		dialog.add_filter(filter)
		if dialog.run == Gtk::Dialog::RESPONSE_ACCEPT
			@filename = dialog.filename
			@book = YAML::load(File.open(@filename))
			@text.formatted_text = @book.chapters[0].text
			$conf.last_file = @filename
			$conf.save
			@chapterlist.refresh_buttons
			self.title = @book.title
		end
		dialog.destroy
	end

private

	def build_window
		self.title = _('Untitled Book')
		self.default_height = $conf.text_width

		full = Gtk::Alignment.new(0.5, 0.5, 0, 1)

		@scroll = Gtk::ScrolledWindow.new
		@scroll.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)
		@text = Text.new
		@scroll.add(@text)

		new = NewBookButton.new
		open = MenuButton.new(Gtk::Stock::OPEN)
		open.tip = _('Open a saved book (Ctrl+O)')
		open.signal_connect('clicked') { open_book }
		save = MenuButton.new(Gtk::Stock::SAVE)
		save.tip = _('Save this book (Ctrl+S)')
		save.signal_connect('clicked') { save_book }
		config = MenuButton.new(Gtk::Stock::PREFERENCES)
		config.tip = _('Open configuration editor (Ctrl+P)')
		config.signal_connect('clicked') do
			c = Configurations.new
			if c.run == Gtk::Dialog::RESPONSE_ACCEPT
				apply_config
			end
			c.destroy
		end
		export = ExportBookButton.new
		begin
			fullscreen = MenuButton.new(Gtk::Stock::FULLSCREEN)
		rescue
			fullscreen = MenuButton.new("#{DIR}/src/fullscreen.png")
		end
		fullscreen.tip = _('Show the book in fullscreen/window (F11)')
		fullscreen.signal_connect('clicked') { go_fullscreen }
		hlp = MenuButton.new(Gtk::Stock::HELP)
		hlp.tip = _('Get help (F1)')
		hlp.signal_connect('clicked') { help }

		@table = Gtk::Table.new(8, 4, false)
		@table.attach(new, 0, 1, 0, 1)
		@table.attach(open, 1, 2, 0, 1)
		@table.attach(save, 2, 3, 0, 1)
		@table.attach(export, 0, 1, 1, 2)
		@table.attach(config, 1, 2, 1, 2)
		@table.attach(fullscreen, 2, 3, 1, 2)
		@table.attach(hlp, 3, 4, 1, 2)
		t_align = Gtk::Alignment.new(0.5, 0, 0, 0)
		t_align << @table

		@chapterlist = ChapterList.new

		@vbox = Gtk::VBox.new(false, 6)
		@vbox.pack_start(t_align, false, false)
		@vbox.pack_start(@separator1 = Gtk::HSeparator.new, false, false)
		@vbox.pack_start(@chapterlist)

		hbox = Gtk::HBox.new
		hbox.pack_start(@scroll)
		hbox.pack_start(@vbox)
		full << hbox
		self << full

		@scroll.vscrollbar_policy = Gtk::POLICY_NEVER
		self.border_width = 6

		self.signal_connect('destroy') do 
			save_book if @filename
			Gtk.main_quit
		end

		add_accelerators

		apply_config

		self.show_all
		@vbox.hide if not $conf.toolbox_visible
	end

	def go_fullscreen
		if @on_fullscreen
	#		@scroll.vscrollbar_policy = Gtk::POLICY_AUTOMATIC
	#		self.height_request = -1
	#		@text.height_request = -1
			self.unfullscreen
			self.resize(@old_size[0], @old_size[1])
			@on_fullscreen = false
		else
			screen = Gdk::Screen.default
			@old_size = self.size
			self.fullscreen
	#		@scroll.vscrollbar_policy = Gtk::POLICY_NEVER
	#		self.height_request = screen.height
	#		@text.height_request = screen.height - 50
			@on_fullscreen = true
		end
	end

	def add_accelerators
		ag = Gtk::AccelGroup.new
		ag.connect(Gdk::Keyval::GDK_F1, nil, Gtk::ACCEL_VISIBLE) { help }
		ag.connect(Gdk::Keyval::GDK_F2, nil, Gtk::ACCEL_VISIBLE) { show_or_hide_toolbox }
		ag.connect(Gdk::Keyval::GDK_N, Gdk::Window::CONTROL_MASK, Gtk::ACCEL_VISIBLE) { NewBookButton.new_book }
		ag.connect(Gdk::Keyval::GDK_O, Gdk::Window::CONTROL_MASK, Gtk::ACCEL_VISIBLE) { open_book }
		ag.connect(Gdk::Keyval::GDK_S, Gdk::Window::CONTROL_MASK, Gtk::ACCEL_VISIBLE) { save_book }
		ag.connect(Gdk::Keyval::GDK_E, Gdk::Window::CONTROL_MASK, Gtk::ACCEL_VISIBLE) { ExportBookButton.export_book }
		ag.connect(Gdk::Keyval::GDK_Q, Gdk::Window::CONTROL_MASK, Gtk::ACCEL_VISIBLE) { save_book; Gtk.main_quit }
		ag.connect(Gdk::Keyval::GDK_P, Gdk::Window::CONTROL_MASK, Gtk::ACCEL_VISIBLE) do
			c = Configurations.new
			if c.run == Gtk::Dialog::RESPONSE_ACCEPT
				apply_config
			end
			c.destroy
		end
		ag.connect(Gdk::Keyval::GDK_Return, Gdk::Window::MOD1_MASK, Gtk::ACCEL_VISIBLE) { go_fullscreen }
		ag.connect(Gdk::Keyval::GDK_F11, nil, Gtk::ACCEL_VISIBLE) { go_fullscreen }
		ag.connect(Gdk::Keyval::GDK_F9, nil, Gtk::ACCEL_VISIBLE) { @chapterlist.current_chapter -= 1 }
		ag.connect(Gdk::Keyval::GDK_F10, nil, Gtk::ACCEL_VISIBLE) { @chapterlist.current_chapter += 1 }
		self.add_accel_group(ag)
	end

	def apply_config
		self.modify_bg(Gtk::STATE_NORMAL, $conf.bg)
		@table.each { |button| button.modify_bg(Gtk::STATE_NORMAL, $conf.bg) }
		@chapterlist.apply_config
		@text.apply_config
		if @book and @book.title
			self.title = @book.title
		else
			self.title = _('Untitled book')
		end
	end

	def help
		h = Help.new([
			['F1', _('Show this help')],
			['F2', _('Show or hide the toolbox')],
			['F9', _('Go to the previous chapter')],
			['F10', _('Go to the next chapter')],
			['F11 or Alt+Enter', _('Full screen')],
			['', ''],
			['Ctrl+N', _('Create a new book')],
			['Ctrl+O', _('Open a saved book')],
			['Ctrl+S', _('Quicksave this book')],
			['Ctrl+E', _('Export this book in a different format')],
			['Ctrl+Q', _('Save and quit')],
			['Ctrl+P', _('Change prefereneces')]])
		h.run
		h.destroy
	end

	def show_or_hide_toolbox
		if @vbox.visible?
			@vbox.hide
		else
			@vbox.show
		end
		$conf.toolbox_visible = @vbox.visible?
		$conf.save
	end

end
